package cn.itcast.nems.manager.enrol;

import cn.itcast.nems.manager.enrol.dto.EnrolApiResult;
import cn.itcast.nems.manager.util.Md5Util;
import cn.itcast.nems.manager.util.OkHttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 报名系统接口
 * author liyong
 * create: 2024-04-07 16:42:00
 **/
public class EnrolManager {
    private final static Logger logger = LoggerFactory.getLogger(EnrolManager.class);
    private final String enrolDomain;
    private final String appId;
    private final String appKey;
    private final ObjectMapper objectMapper;

    public EnrolManager(String enrolDomain, String appId, String appKey) {
        this.enrolDomain = enrolDomain;
        this.appId = appId;
        this.appKey = appKey;
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 取消报名系统订单
     *
     * @param studentId 学员ID
     * @param clazzId   班级ID
     */
    public EnrolApiResult cancelOrder(int studentId, int clazzId) {
        Map<String, Object> params = new HashMap<>();
        params.put("studentId", studentId);
        params.put("clazzId", clazzId);
        final String response = this.doPost(params, "/enrol/emsapi/stu/order/cancel");
        try {
            return this.objectMapper.readValue(response, EnrolApiResult.class);
        } catch (Exception e) {
            String msg = String.format("取消报名系统订单出现错误，studentId %d, clazzId %d 异常信息: %s", studentId, clazzId, e.getMessage());
            logger.warn(msg, e);
            EnrolApiResult result = new EnrolApiResult();
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage(msg);
            return result;
        }
    }

    private String doPost(Map<String, Object> params, String apiPath) {
        params.put("enrolId", this.appId);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        String sig = Md5Util.calSignature(new TreeMap<>(params), this.appKey);
        params.put("sign", sig);
        String url = this.enrolDomain + apiPath;
        logger.warn("request enrol url:{} params:{}", url, params);
        String response = OkHttpUtil.doPost(url, params);
        logger.warn("enrol response:{}", response);
        return response;
    }
}
